package com.shg.bean;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class BuyCart implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	//ID号
	private String id;
	//将对象通过JSON转换后的文本内容
	private String content;
	//生命期
	private Date life;
	//购物车所属用户
	private Users user;
	//购物项
	private List<BuyItem> items=new ArrayList<BuyItem>();

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public Users getUser() {
		return user;
	}

	public void setUser(Users user) {
		this.user = user;
	}
	public List<BuyItem> getItems() {
		return items;
	}

	/**
	 * 将数据库里面的String字符串转为数组
	 * @return
	 */
	public List<BuyItem> initList(){
		//首先将内容转为数组
		JSONArray jsonArray=JSONArray.fromObject(this.content);
		List<BuyItem> buyItems = (ArrayList<BuyItem>) JSONArray.toList(jsonArray);
		//在将数组转为对象
		for(int i=0;i<buyItems.size();i++){
			JSONObject jsonObject=JSONObject.fromObject(buyItems.get(i));
			BuyItem buyItem = (BuyItem) JSONObject.toBean(jsonObject, BuyItem.class);
			items.add(buyItem);
		}
		return items;
	}
	/**
	 * 添加购物项
	 * @param item
	 */
	public void addItem(BuyItem item){
		if(items.contains(item)){
			for(BuyItem buyItem:items){
				if(buyItem.equals(item)){
					buyItem.setCount(buyItem.getCount()+1);
				}
			}
		}else{
			items.add(item);
		}
		this.content=JSONArray.fromObject(this.items).toString();
	}
	/**
	 * 修改购买数量
	 * @return
	 */
	public void changeCount(BuyItem buyItem){
		for(BuyItem item:items){
			if(buyItem.equals(item)){
				item.setCount(buyItem.getCount());
			}
		}
		this.content=JSONArray.fromObject(this.items).toString();
	}
	public Date getLife() {
		long day=6*30*24;
		long minus=60*60*1000;
		this.life=new Date();
		this.life.setTime(this.life.getTime()+day*minus);
		return life;
	}

	public void setLife(Date life) {
		this.life=life;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		BuyCart other = (BuyCart) obj;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		return true;
	}
	
}
